// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env:"cloud2-4gncvam39e2323e9",
})
const db=cloud.database();
const _ = db.command;
// 云函数入口函数
exports.main = async (event, context) => {
  const openid = cloud.getWXContext().OPENID
  event.openid=openid
 
  var res= await db.collection("lastchat").where({
    openid2:event.openid2,
    openid1:event.openid1
  }).count()
  if(res.total>0){//已有数据
    if(openid==event.openid1){//发信人或者进入了聊天室
      event.notread=0
    }
    else{
      if(event.toroom==1){
        event.notread=0
      }
      else{
      event.notread=_.inc(1)
      }
    }
    await db.collection('lastchat').where({
      openid2:event.openid2,
      openid1:event.openid1
    }).update({
      data: event
    })
  }else {
    if(event.toroom==0){
      if(openid==event.openid1){//发信人
        event.notread=0
      }
     else{
        event.notread=1
     }
     await db.collection('lastchat').add({
        data: event
      })
  }
}
}
  